package controllers

import (
	"github.com/revel/revel"
	"waterblabla/app/models"
)

type Order struct {
	Controller
}

func (c Order) AcceptOrder() revel.Result {
	type Req struct {
		models.QS `,inline valid:"Required"`
		OrderID   string          `json:"orderID" valid:"Required"`
		Postman   *models.Postman `valid:"Required"`
		Type      int             `json:"type" valid:"Required"`
	}

	// parse
	var req Req
	if err := models.ParseBodyAndValidate(c.body, &req); err != nil {
		return c.RenderResult(err)
	}

	return c.RenderResult(models.AcceptOrder(req.QS.Qid, req.OrderID, *req.Postman, req.Type))
}

func (c Order) CompleteOrder() revel.Result {
	type Req struct {
		models.QS    `,inline`
		OrderID      string `json:"orderID"  valid:"Required"`
		SentBuckets  int    `json:"sentBuckets"`
		ReturnBotles int    `json:"returnBotles"`
		Sn           string `json:"sn"  valid:"Required"`
		Comment      string `json:"comment"`
	}
	// parse
	var req Req
	if err := models.ParseBodyAndValidate(c.body, &req); err != nil {
		return c.RenderResult(err)
	}
	if err := models.CompleteOrder(req.OrderID, req.Sn, req.SentBuckets,
		req.ReturnBotles, req.Comment); err != nil {
		return c.RenderResult(err)
	}
	return c.RenderResult(nil)
}

func (c Order) Orders() revel.Result {
	type Req struct {
		models.QS `,inline`
		StationID string   `json:"stationID"`
		Count     int      `json:"count"  valid:"Required"`
		Cursor    int64    `json:"cursor" valid:"Required"`
		CursorEnd int64    `json:"cursorEnd"`
		State     int      `json:"state" valid:"Required"`
		Postman   []string `json:"postman"`
		Customer  []string `json:"customer"`
		Brands    []string `json:"brands"`
	}
	// parse
	var req Req
	if err := models.ParseBodyAndValidate(c.body, &req); err != nil {
		return c.RenderResult(err)
	}
	var orders []models.Order
	if err := models.GetOrders(req.QS.Qid, req.StationID, req.Count, req.State,
		req.Postman, req.Customer, req.Cursor, req.CursorEnd, &orders); err != nil {
		return c.RenderResult(err)
	}

	return c.RenderResult(orders)
}

func (c Order) PostmanOrders() revel.Result {
	type Req struct {
		models.QS `,inline`
		Count     int   `json:"count" valid:"Required"`
		Cursor    int64 `json:"cursor" valid:"Required"`
	}
	// parse
	var req Req
	if err := models.ParseBodyAndValidate(c.body, &req); err != nil {
		return c.RenderResult(err)
	}
	var orders []models.Order
	if err := models.GetPostmanOrders(req.QS.Qid, req.Count, req.Cursor, &orders); err != nil {
		return c.RenderResult(err)
	}

	return c.RenderResult(orders)
}
